#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@FileName: find_section.py
@Version: 1.0
@Date: 2023/6/21 15:43
@Description: 寻找函数零点的区间
"""
import math
from root_paras import Paras


def find_section(fun, paras: Paras = Paras()) -> tuple[float, float]:
    """
    找出迭代区间, 左右延伸法
    itv_tol: 区间精度
    """
    start = paras.start
    sol_tol = paras.sol_tol
    loops = paras.loops

    left: list[float] = [start, start]
    right: list[float] = [start, start]
    step: float = paras.dft_sect
    if math.fabs(fun(start)) <= sol_tol:  # orig 是解，完成
        return start, start

    n: int = 0
    while True:
        n += 1
        if n > loops:
            raise RuntimeError(f'Can not find section after {loops} loops')

        left[0] = left[1]
        right[0] = right[1]
        left[1] = start - step
        right[1] = start + step

        # 左向搜索
        if fun(left[1]) * fun(left[0]) <= 0.0:
            return left[1], left[0]
        # 右向搜索
        if fun(right[1]) * fun(right[0]) <= 0.0:
            return right[0], right[1]
        step *= 2


if __name__ == '__main__':
    res = find_section(lambda x: x ** 3 + x - 1)
    print(res)
